<template>
  <div class="prize-manage">
    <div class="page-header">
      <h2>奖品列表管理</h2>
      <p>管理抽奖活动中的所有奖品信息</p>
    </div>

    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="奖品名称">
          <el-input v-model="searchForm.name" placeholder="请输入奖品名称" clearable />
        </el-form-item>
        <el-form-item label="奖品分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="实物奖品" value="实物奖品" />
            <el-option label="虚拟奖品" value="虚拟奖品" />
            <el-option label="现金奖品" value="现金奖品" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增奖品
      </el-button>
      <el-button @click="refreshData">
        <el-icon>
          <Refresh />
        </el-icon>
        刷新
      </el-button>
    </div>

    <el-table :data="tableData" v-loading="loading" stripe>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="image" label="奖品图片" width="100">
        <template #default="{ row }">
          <el-image :src="row.image" :preview-src-list="[row.image]" fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px;" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="奖品名称" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="value" label="奖品价值" width="120">
        <template #default="{ row }">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ row.value }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="库存数量" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="奖品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入奖品名称" />
        </el-form-item>
        <el-form-item label="奖品分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类">
            <el-option label="实物奖品" value="实物奖品" />
            <el-option label="虚拟奖品" value="虚拟奖品" />
            <el-option label="现金奖品" value="现金奖品" />
          </el-select>
        </el-form-item>
        <el-form-item label="奖品价值" prop="value">
          <el-input-number v-model="formData.value" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="库存数量" prop="quantity">
          <el-input-number v-model="formData.quantity" :min="0" />
        </el-form-item>
        <el-form-item label="奖品图片" prop="image">
          <el-input v-model="formData.image" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="奖品描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入奖品描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const editId = ref<number | null>(null)

// 表单数据
const formData = reactive({
  name: '',
  category: '',
  value: 0,
  quantity: 0,
  image: '',
  description: '',
  status: '启用'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入奖品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '奖品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择奖品分类', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入奖品价值', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请输入奖品图片URL', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    name: 'iPhone 15 Pro',
    category: '实物奖品',
    value: 7999.00,
    quantity: 5,
    image: 'https://via.placeholder.com/60x60?text=iPhone',
    description: '苹果最新旗舰手机',
    status: '启用',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    name: '100元优惠券',
    category: '虚拟奖品',
    value: 100.00,
    quantity: 50,
    image: 'https://via.placeholder.com/60x60?text=券',
    description: '全场通用优惠券',
    status: '启用',
    createTime: '2024-01-14 15:20:00'
  },
  {
    id: 3,
    name: '现金红包',
    category: '现金奖品',
    value: 288.00,
    quantity: 20,
    image: 'https://via.placeholder.com/60x60?text=红包',
    description: '微信现金红包',
    status: '启用',
    createTime: '2024-01-13 09:45:00'
  },
  {
    id: 4,
    name: 'MacBook Pro',
    category: '实物奖品',
    value: 12999.00,
    quantity: 2,
    image: 'https://via.placeholder.com/60x60?text=Mac',
    description: '苹果笔记本电脑',
    status: '禁用',
    createTime: '2024-01-12 16:30:00'
  }
]

// 获取数据
const fetchData = () => {
  loading.value = true

  // 模拟API请求
  setTimeout(() => {
    let filteredData = [...mockData]

    // 应用搜索条件
    if (searchForm.name) {
      filteredData = filteredData.filter(item =>
        item.name.toLowerCase().includes(searchForm.name.toLowerCase())
      )
    }
    if (searchForm.category) {
      filteredData = filteredData.filter(item => item.category === searchForm.category)
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }

    tableData.value = filteredData
    total.value = filteredData.length
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.status = ''
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  fetchData()
  ElMessage.success('数据已刷新')
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchData()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

// 新增奖品
const handleAdd = () => {
  dialogTitle.value = '新增奖品'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑奖品
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑奖品'
  isEdit.value = true
  editId.value = row.id

  // 填充表单数据
  formData.name = row.name
  formData.category = row.category
  formData.value = row.value
  formData.quantity = row.quantity
  formData.image = row.image
  formData.description = row.description
  formData.status = row.status

  dialogVisible.value = true
}

// 删除奖品
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除奖品"${row.name}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 模拟API请求
    setTimeout(() => {
      submitLoading.value = false
      dialogVisible.value = false

      if (isEdit.value) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.success('新增成功')
      }

      fetchData()
    }, 1000)

  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  formData.name = ''
  formData.category = ''
  formData.value = 0
  formData.quantity = 0
  formData.image = ''
  formData.description = ''
  formData.status = '启用'
  editId.value = null

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.prize-manage {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-bar {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
